package boundarys;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.List;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;

import ccrm.BoundryControl;
import controllers.CreateProductController;
import entitys.Reply;
import enums.Result;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;

import javax.swing.JComboBox;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

public class CreateProductGUI extends AbstractGUI{
	/**
	 * Create Product frame/ 
	 */
	private JFrame frmCR; //Create Product frame
	/**
	 *  Text field for name of product.
	 */
	private JTextField NameTextField;
	/**
	 * Text field for the price of the product.
	 */
	private JTextField PriceTextField;
	/**
	 * Asterisk text field for marking Users mistakes on screen.
	 */
	private final JLabel nameHash = new JLabel("*");
	/**
	 * ComboBox of preDefined picture for the user to choose and match to product.
	 */	
	JComboBox picutreComboBox=null;
	/**
	 * Label that show the selected picutre from the ComboBox. 
	 */
	JLabel lblPiclable=null;
	/**
	 * Create Product constructor
	 */
	public CreateProductGUI() {
		initialize();
		initGUI(frmCR);
		
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmCR = new JFrame();

	//	frmCR.setEnabled(false);
		frmCR.setTitle("...Define Product>Create Product");
		frmCR.setBounds(100, 100, 314, 427);
		frmCR.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frmCR.getContentPane().setLayout(null);
		
		JLabel lblName = new JLabel("Name :");
		lblName.setBounds(10, 27, 87, 14);
		frmCR.getContentPane().add(lblName);
		
		JLabel lblPrice = new JLabel("Price :");
		lblPrice.setBounds(10, 52, 64, 14);
		frmCR.getContentPane().add(lblPrice);
		
		JLabel lblPicture = new JLabel("Picture :");
		lblPicture.setBounds(10, 77, 64, 14);
		frmCR.getContentPane().add(lblPicture);
		
		JLabel lblDescription = new JLabel("Description :");
		lblDescription.setBounds(10, 266, 87, 14);
		frmCR.getContentPane().add(lblDescription);
		
		NameTextField = new JTextField();
		NameTextField.setBounds(107, 24, 159, 20);
		frmCR.getContentPane().add(NameTextField);
		NameTextField.setColumns(10);
		
		PriceTextField = new JTextField();
		PriceTextField.setBounds(107, 49, 159, 20);
		frmCR.getContentPane().add(PriceTextField);
		PriceTextField.setColumns(10);
		

		//DescripTextField.setColumns(10);
		
		JButton btnConfirm = new JButton("Confirm");

		btnConfirm.setBounds(177, 356, 89, 23);
		frmCR.getContentPane().add(btnConfirm);
		
		JButton btnCancel = new JButton("Cancel");
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) { //cancel product
				frmCR.setVisible(false);
				goBack();
			}
		});
		btnCancel.setBounds(10, 356, 89, 23);
		frmCR.getContentPane().add(btnCancel);
		nameHash.setBounds(270, 23, 15, 23);
		frmCR.getContentPane().add(nameHash);
		nameHash.setVisible(false);
		JLabel priceHash = new JLabel("*");
		priceHash.setForeground(Color.RED);
		nameHash.setForeground(Color.RED);
		priceHash.setBounds(270, 49, 15, 23);
		frmCR.getContentPane().add(priceHash);
		
		JEditorPane DescripTextField = new JEditorPane();
		DescripTextField.setBounds(107, 266, 159, 78);
		frmCR.getContentPane().add(DescripTextField);
		
	


		

		
		


		
		lblPiclable = new JLabel("");
		lblPiclable.setBounds(10, 105, 256, 150);
		frmCR.getContentPane().add(lblPiclable);
		
		picutreComboBox = new JComboBox();
	
		
		picutreComboBox.setBounds(107, 74, 159, 20);
		picutreComboBox.addItem("Please select an image");
		getPicturesList();
		frmCR.getContentPane().add(picutreComboBox);
		

		picutreComboBox.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent arg0) {
				BufferedImage myPicture = null;
				
				if(picutreComboBox.getSelectedItem()==null )
					return;
				try {
					if(picutreComboBox.getSelectedIndex()==0)
					{
						frmCR.getContentPane().remove(lblPiclable);
						frmCR.getContentPane().validate();
						frmCR.getContentPane().repaint();
						lblPiclable = new JLabel("");
						lblPiclable.setBounds(10, 105, 256, 150);
						frmCR.getContentPane().add(lblPiclable);
						frmCR.getContentPane().revalidate();
						frmCR.getContentPane().repaint();
						return;
					}
					myPicture = ImageIO.read(new File("images\\"+picutreComboBox.getSelectedItem()+".png"));
					
				
			
				Image myPictureScaled=myPicture.getScaledInstance(lblPiclable.getWidth(), lblPiclable.getHeight(), myPicture.SCALE_SMOOTH);
				frmCR.getContentPane().remove(lblPiclable);
				frmCR.getContentPane().validate();
				frmCR.getContentPane().repaint();
				lblPiclable = new JLabel(new ImageIcon(myPictureScaled));
				lblPiclable.setBounds(10, 105, 256, 150);
				frmCR.getContentPane().add(lblPiclable);
				frmCR.getContentPane().revalidate();
				frmCR.getContentPane().repaint();
				} catch (IOException e1) {
					System.out.println("Picture isn't defined.");
				}
				catch (java.lang.NullPointerException e1)
				{
					System.out.println("picture wasn't found.");
				}
			}
		});
		priceHash.setVisible(false);
		btnConfirm.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) { //confirm product & add to DB
				if(!NameTextField.getText().trim().equals(""))
				{
				try
				{
					CreateProductController.addProduct(NameTextField.getText(), DescripTextField.getText(), ((picutreComboBox.getSelectedIndex()!=0)?picutreComboBox.getSelectedItem().toString():null), Float.parseFloat(PriceTextField.getText())); //ask Controller to send ADD_PRODUCT request
					priceHash.setVisible(false);
					nameHash.setVisible(false);
				}
				catch( java.lang.NumberFormatException ex)
				{
					priceHash.setVisible(true);
				}
				}
				else
				nameHash.setVisible(true);
			}
		});
		frmCR.setVisible(true);
	}

	@Override
	/**
	 * AbstractGUI overridden method for getting a reply from server 
	 */
	public void getReply(Object r) { //get reply from server
		Result result= (Result) ((Reply)r).result;
		if(result.equals(Result.OK))
		{
			System.out.println(result.toString());
			JOptionPane.showMessageDialog(frmCR, "Product created!", "CCRM>Create product", JOptionPane.INFORMATION_MESSAGE);
			this.goBack();
		
		}
		
		else if(result.equals(Result.FAILED))
		{
			System.out.println("Unable to add an existing product!");
			JOptionPane.showMessageDialog(frmCR, "Unable to create an existing product!", "CCRM>Create product", JOptionPane.ERROR_MESSAGE);
		}
		
		
	}
	/**
	 * Search "Images" folder for ".png" files. 
	 */
	private void getPicturesList()
	{
		File dir = new File("images");
		ArrayList<String> picList = new ArrayList<String>();
		if (dir.isDirectory()) {
		  String[] files = dir.list();
		  Pattern p1 = Pattern.compile("^(.*?)\\.png$");

		  for (String file : files) {
		    Matcher m1 = p1.matcher(file);

		    if (m1.matches()) {
		    	picList.add(m1.group(1));
		    }

		  }
		}
		for(int i=0;i<picList.size();i++)
			picutreComboBox.addItem(picList.get(i));
	
		frmCR.getContentPane().repaint();

	}
	
}


